import React, { useEffect, useRef } from 'react';
import { Card, Table, Typography, Row, Col } from 'antd';
import * as echarts from 'echarts';

const { Title, Text } = Typography;

// 生成过去7天的日期
const generateDates = (days = 7) => {
  const dates = [];
  for (let i = days - 1; i >= 0; i--) {
    const date = new Date();
    date.setDate(date.getDate() - i);
    dates.push(date.toISOString().split('T')[0]);
  }
  return dates;
};

const dates = generateDates();

// 模拟数据
const mockData = [
  ...dates.map(date => ({ date, behavior_type: '浏览', count: Math.floor(Math.random() * 10000) + 5000 })),
  ...dates.map(date => ({ date, behavior_type: '点击', count: Math.floor(Math.random() * 8000) + 3000 })),
  ...dates.map(date => ({ date, behavior_type: '加入购物车', count: Math.floor(Math.random() * 2000) + 500 })),
  ...dates.map(date => ({ date, behavior_type: '购买', count: Math.floor(Math.random() * 1000) + 200 })),
  ...dates.map(date => ({ date, behavior_type: '收藏', count: Math.floor(Math.random() * 1500) + 300 })),
];

const behaviorTypes = ['浏览', '点击', '加入购物车', '购买', '收藏'];

const columns = [
  {
    title: '日期',
    dataIndex: 'date',
    key: 'date',
  },
  {
    title: '行为类型',
    dataIndex: 'behavior_type',
    key: 'behavior_type',
  },
  {
    title: '数量',
    dataIndex: 'count',
    key: 'count',
  },
];

const DailyBehaviorStats = () => {
  const lineChartRef = useRef(null);
  const pieChartRef = useRef(null);
  const lineChartInstance = useRef(null);
  const pieChartInstance = useRef(null);

  useEffect(() => {
    // 初始化折线图
    if (lineChartRef.current && !lineChartInstance.current) {
      lineChartInstance.current = echarts.init(lineChartRef.current);
    }

    // 初始化饼图
    if (pieChartRef.current && !pieChartInstance.current) {
      pieChartInstance.current = echarts.init(pieChartRef.current);
    }

    // 准备折线图数据
    const lineSeries = behaviorTypes.map(type => ({
      name: type,
      type: 'line',
      smooth: true,
      data: dates.map(date => {
        const item = mockData.find(d => d.date === date && d.behavior_type === type);
        return item ? item.count : 0;
      })
    }));

    // 准备饼图数据（使用最新一天的数据）
    const latestDate = dates[dates.length - 1];
    const pieData = behaviorTypes.map(type => {
      const item = mockData.find(d => d.date === latestDate && d.behavior_type === type);
      return {
        name: type,
        value: item ? item.count : 0
      };
    });

    // 折线图配置
    const lineOption = {
      title: {
        text: '每日行为统计趋势',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: behaviorTypes,
        bottom: 10
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: dates
      },
      yAxis: {
        type: 'value'
      },
      series: lineSeries
    };

    // 饼图配置
    const pieOption = {
      title: {
        text: `最新日期(${latestDate})行为分布`,
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: behaviorTypes
      },
      series: [
        {
          name: '行为类型',
          type: 'pie',
          radius: '50%',
          data: pieData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };

    // 渲染图表
    if (lineChartInstance.current) {
      lineChartInstance.current.setOption(lineOption);
    }
    if (pieChartInstance.current) {
      pieChartInstance.current.setOption(pieOption);
    }

    // 响应式调整
    const handleResize = () => {
      if (lineChartInstance.current) {
        lineChartInstance.current.resize();
      }
      if (pieChartInstance.current) {
        pieChartInstance.current.resize();
      }
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
      if (lineChartInstance.current) {
        lineChartInstance.current.dispose();
        lineChartInstance.current = null;
      }
      if (pieChartInstance.current) {
        pieChartInstance.current.dispose();
        pieChartInstance.current = null;
      }
    };
  }, []);

  // 计算统计信息
  const totalCountByType = behaviorTypes.map(type => {
    const total = mockData
      .filter(d => d.behavior_type === type)
      .reduce((sum, item) => sum + item.count, 0);
    return { type, total };
  });

  return (
    <div>
      <Title level={4}>每日行为统计数据</Title>
      <Row gutter={[16, 16]}>
        <Col span={24}>
          <Card>
            <div ref={lineChartRef} style={{ width: '100%', height: 400 }} />
          </Card>
        </Col>
        <Col xs={24} lg={8}>
          <Card>
            <div ref={pieChartRef} style={{ width: '100%', height: 300 }} />
          </Card>
        </Col>
        <Col xs={24} lg={16}>
          <Card>
            <Title level={5}>行为统计信息</Title>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 20 }}>
              {totalCountByType.map((item, index) => (
                <div key={index} style={{ textAlign: 'center' }}>
                  <Text strong style={{ fontSize: 18 }}>{item.type}</Text>
                  <div style={{ fontSize: 24, fontWeight: 'bold', marginTop: 10 }}>
                    {item.total.toLocaleString()}
                  </div>
                  <Text type="secondary">总次数</Text>
                </div>
              ))}
            </div>
            <div style={{ marginTop: 20, textAlign: 'center' }}>
              <Text strong style={{ fontSize: 20 }}>
                总行为次数: {totalCountByType.reduce((sum, item) => sum + item.total, 0).toLocaleString()}
              </Text>
            </div>
          </Card>
        </Col>
      </Row>
      <Card style={{ marginTop: 20 }}>
        <Title level={5}>详细数据列表</Title>
        <Table columns={columns} dataSource={mockData} rowKey={(record) => `${record.date}-${record.behavior_type}`} pagination={{ pageSize: 15 }} />
      </Card>
    </div>
  );
};

export default DailyBehaviorStats;